package cn.wolfcode.crm.shiro;

import cn.wolfcode.crm.util.JsonResult;
import com.alibaba.fastjson.JSON;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.stereotype.Component;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;

//登录用的是ajax来提交数据的，异步请求不能重定向的，
// Shiro两种默认处理方式都不符合，所以我们选择通过继承FormAuthenticationFilter，
// 重写方法onLoginSuccess、onLoginFailure来实现具体的需求
@Component("crmFormAuthenticationFilter")
public class AjaxFormAuthenticationFilter extends FormAuthenticationFilter {
    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
        JsonResult jsonResult = new JsonResult();
        //使用response对象输出数据（JSON字符串）
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().print(JSON.toJSONString(jsonResult));
        return false;  //不放行
    }

    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        e.printStackTrace();//打印异常信息：方便定位异常

        //对应不同的异常提示不同的信息
        String msg = "登录异常，请联系管理员！";
        if (e instanceof UnknownAccountException) {
            msg = "账号不存在！";
        } else if (e instanceof IncorrectCredentialsException) {
            msg = "密码错误！";
        }

        JsonResult jsonResult = new JsonResult(false, msg);
        //使用response对象输出数据（JSON字符串）
        response.setContentType("application/json;charset=utf-8");
        try {
            response.getWriter().print(JSON.toJSONString(jsonResult));
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return false;  //不放行
    }
}
